<?php
namespace App\Http\Controllers\Backend;

use App\Http\Controllers\BaseBackendController;
use App\Models\Admin;
use Illuminate\Http\Request;
use App\Services\ResponseService;
use Illuminate\Support\Facades\Cookie;

class LoginController extends BaseBackendController
{
    CONST LOGIN_EMPTY_CODE = 100001;
    CONST LOGIN_EMPTY_MESSAGE = "用户名或密码为空";
    CONST LOGIN_FAIL_CODE = 100002;
    CONST LOGIN_FAIL_MESSAGE = "用户名或密码错误";
    CONST COOKIE_LOGIN_KEY = '_secureu';

    public function index()
    {
        return view('backend.login');
    }

    public function login(Request $request)
    {
        $username = $request->get('username');
        $password = $request->get('password');
        if ($username && $password) {
            $info = Admin::where('username', $username)->where('password', $password)->first();
            if ($info) {
                //设置cookie有效期为一个月
                $cookieData = $this->cookieData('login', self::COOKIE_LOGIN_KEY, $info['id'], 24 * 60 * 30);
                return ResponseService::returnJson(ResponseService::SUCCESS, ['message' => ResponseService::LOGIN_SUCCESS_MESSAGE, 'url' => route('backendIndex')], $cookieData);
            } else {
                return ResponseService::returnJson(self::LOGIN_FAIL_CODE, ['message' => self::LOGIN_FAIL_MESSAGE]);
            }
        } else {
            return ResponseService::returnJson(self::LOGIN_EMPTY_CODE, ['message' => self::LOGIN_EMPTY_MESSAGE]);
        }
    }
}